<?php

namespace app\admin\controller\medicine;

use app\common\controller\Backend;
use think\Db;

/**
 * 药品信息维护管理
 *
 * @icon fa fa-circle-o
 */
class Medicine extends Backend
{

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Medicine;

        $supplier = Db::table('fa_supplier')
            ->select();
        $this->view->assign("supplier", $supplier);
    }

    /**
     * 查看
     */
    public function index()
    {

//        //设置过滤方法
//        $this->request->filter(['strip_tags', 'trim']);
//        if ($this->request->isAjax()) {
//
//            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//
//            $list = $this->model
//                ->where($where)
//                ->where('is_del', 0)
//                ->order('id', $order)
//                ->paginate($limit);
//
//            $result = array("total" => $list->total(), "rows" => $list->items());
//
//            return json($result);
//        }

        return $this->view->fetch();
    }


    public function table1()
    {
        $this->model = model('Medicine');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('is_del', 0)
                //->order('id', $order)
                ->order('id', 'desc')
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch('index');
    }

    public function table2()
    {
        $this->model = model('Medicine');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('is_del', 1)
                ->order(['update_time'=>'desc','id'=>'desc'])
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch('index');
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $count = Db::table('fa_medicine')
                    ->count();

                $params['code'] = 'YLQX-'.($count+1);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 详情
     */
    public function detail($ids)
    {
        $row = $this->model->get(['id' => $ids]);

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 软删除
     *
     */
    public function del_s($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $pan = explode(',',$ids);
        if (count($pan) > 1){
            foreach ($pan as $k=>$v){
                $pan_arr = Db::table('fa_drug')
                    ->alias('a')
                    ->field('a.id,b.id as bid,a.order_id,c.id as cid')
                    ->join('fa_treatment b','a.order_id=b.order_id')
                    ->join('fa_storage c','a.medicine_id=c.id')
                    ->where(['c.medicine_id'=>$v,'b.get'=>0])
                    ->find();

                $name_arr = Db::table('fa_medicine')
                    ->field('id,medicine_name')
                    ->where('id',$v)
                    ->find();

                $order_arr = Db::table('fa_diagnosis_order')
                    ->field('code')
                    ->where('id',$pan_arr['order_id'])
                    ->find();


                if (!empty($pan_arr)){
                    $this->error(__($name_arr['medicine_name'].',该药品在订单:'.$order_arr['code'].'中有数据,请领取或删除该药品再操作。'));
                }
            }

        }else{
            $pan_arr = Db::table('fa_drug')
                ->alias('a')
                ->field('a.id,b.id as bid,a.order_id,c.id as cid')
                ->join('fa_treatment b','a.order_id=b.order_id')
                ->join('fa_storage c','a.medicine_id=c.id')
                ->where(['c.medicine_id'=>$ids,'b.get'=>0])
                ->find();

            $order_arr = Db::table('fa_diagnosis_order')
                ->field('code')
                ->where('id',$pan_arr['order_id'])
                ->find();

            if (!empty($pan_arr)){
                $this->error(__($row->medicine_name.',该药品在订单:'.$order_arr['code'].'中有数据,请领取或删除该药品再操作。'));
            }
        }

        $del = Db::table('fa_medicine')
            ->where('id','in',$ids)
            ->update([
                'is_del' => 1,
                'update_time' => time(),
            ]);

        if ($del !== false){
            $this->success();
        }else{
            $this->error(__('No rows were updated'));
        }

    }


}
